﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AIMLbot;
using BlackBoard;
namespace BotAdapter
{
    public class BotAdapter
    {
        private User user;
        private Bot yeti;
        private BlackBoard.BlackBoard blackBoard;
        private ConversationStage conversationStage;

        public BotAdapter(String userName, String botPath)
        {
            yeti = new Bot();
            yeti.loadSettings(botPath);
            yeti.loadAIMLFromFiles();

            user = new User(userName, yeti);

            blackBoard = new BlackBoard.BlackBoard();
        }

        public ConversationStage Chat(String userInput)
        {
            conversationStage = new ConversationStage();

            try
            {
                var pattern = blackBoard.FirstRun(userInput);
                var request = new Request(pattern, user, yeti);
                var result = yeti.Chat(request);

                if (!result.Output.Equals("Przepraszam, ale Cie nie rozumiem."))
                {
                    conversationStage.userInput = userInput;
                    conversationStage.pattern = pattern;
                    conversationStage.response = result.Output;
                    return conversationStage;
                }
                else
                {
                    var patterns = blackBoard.Run(userInput);
                    foreach (var p in patterns)
                    {
                        request = new Request(p, user, yeti);
                        result = yeti.Chat(request);

                        if (!result.Output.Equals("Przepraszam, ale Cie nie rozumiem."))
                        {
                            conversationStage.userInput = userInput;
                            conversationStage.pattern = p;
                            conversationStage.response = result.Output;

                            return conversationStage;
                        }

                    }
                    conversationStage.userInput = userInput;
                    conversationStage.pattern = pattern;
                    conversationStage.response = "Przepraszam, ale Cie nie rozumiem.";
                    return conversationStage;
                }
            }
            catch (System.Exception ex)
            {
                conversationStage.userInput = userInput;
                conversationStage.pattern = userInput;
                conversationStage.response = "No tak to nie porozmawiamy...";
                return conversationStage;
            }
            
            
        }
    }
}